//
//  IntegralConllectionView.m
//  Base_App
//
//  Created by Yutian Duan on 2019/6/4.
//  Copyright © 2019年 Wanwin. All rights reserved.
//

#import "IntegralConllectionView.h"
#import "IntegralConllectionViewCell.h"

#define ITEMCELLID  @"ITEMCELLID"

@interface IntegralConllectionView () <UICollectionViewDelegate,UICollectionViewDataSource> {
  CGFloat offsetLeft;
  CGFloat ItemW;
  
  CGFloat          startX;
  CGFloat          endX;
  
}

@end

@implementation IntegralConllectionView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
  self = [super initWithFrame:frame collectionViewLayout:layout];
  if (self) {
    CardCollectionViewLayout *Itemlayout = (CardCollectionViewLayout *)layout;
    ItemW = Itemlayout.itemSize.width;
    offsetLeft = (ScreenWidth - ItemW)/2;
    self.backgroundColor = HEXCOLOR(0xf7f8fc);
    self.delegate = self;
    self.dataSource = self;
    self.showsHorizontalScrollIndicator = NO;
    [self registerClass:[IntegralConllectionViewCell class] forCellWithReuseIdentifier:ITEMCELLID];
    
  }
  return self;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
  return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  return _imageArray.count;
}

// 间隔
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
  return UIEdgeInsetsMake(0, offsetLeft, 0, offsetLeft);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  
  IntegralConllectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ITEMCELLID forIndexPath:indexPath];
  cell.imageIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",_imageArray[indexPath.row]]];
  return cell;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
  startX = scrollView.contentOffset.x;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
  endX = scrollView.contentOffset.x;
  dispatch_async(dispatch_get_main_queue(), ^{
    [self cellToCenter];
  });
}

- (void)cellToCenter {
  //最小滚动距离
  float  dragMinDistance = self.bounds.size.width/40.0f;
  if (startX - endX >= dragMinDistance) {
    _currentIndex -= 1; //向右
  }else if (endX - startX >= dragMinDistance){
    _currentIndex += 1 ;//向左
  }
  NSInteger maxIndex  = [self numberOfItemsInSection:0] - 1;
  _currentIndex = _currentIndex <= 0 ? 0 :_currentIndex;
  _currentIndex = _currentIndex >= maxIndex ? maxIndex : _currentIndex;
  
  
  [self scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
  
}

@end
